<template>
  <div class="sms-message-page" :style="{padding:showNav?'16px':'0'}">
    <div class="sms-message-page-content">
      <div v-if="showNav" class="left-menu">
        <div class="menu-title">消息设置</div>
        <div v-for="(item, index) in newMenuList" :key="index">
          <nav :class="`menu-list ${nowMenu == index ? 'menu-checked' : ''}`" @click="changePage(item, index)">
            <div class="icon-box">
              <i :class="`iconfont ${item.icon} ${nowMenu == index ? 'font-16 font-w-600' : 'font-14'}`"></i>
            </div>
            <span>{{ item.name }}</span>
          </nav>
        </div>
      </div>
      <div class="main" ref="mainRef">
        <div class="sms-message-tpl">
          <!-- 工单响应通知 start-->
          <div class="setting-item task-response-item">
            <div class="header">
              <div class="title">
                工单响应通知 <el-tooltip content="尊敬的客户您好，{tenant}计划{time}安排{user}联系电话{umobile}为您提供服务，客服电话{phone}。"><i class="iconfont icon-fdn-info"></i></el-tooltip> 
              </div>
              <div class="switch-contain">
								<el-switch
                  v-model="messageConfig.smsTaskResponse"
                  @change="changeState($event, 'smsTaskResponse')"
                />
								<div class="desc">当工单被接受时，发送给客户联系人</div>
							</div>
            </div>
            <div class="scope">
              <h6>应用范围</h6>
              <el-select
                v-model="messageConfig.taskResponseTaskTypeList"
                size="mini"
                multiple
                clearable
                collapse-tags
                style="width: 190px"
                placeholder="全部工单类型"
                @change="typeSelectChange('taskResponseTaskTypeList')"
              >
                <el-option v-for="item in taskTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>
          </div>
          <!-- 工单响应通知 end-->

          <!-- 工单完成通知 start-->
          <div class="setting-item">
            <div class="header">
              <div class="title">
                工单完成通知 <el-tooltip content="尊敬的客户您好，{tenant}员工{user}联系电话{umobile}已经为您完成了服务，感谢您的协助，客服电话{phone}。"><i class="iconfont icon-fdn-info"></i></el-tooltip> 
              </div>
              <div class="switch-contain">
                <el-switch
                  v-model="messageConfig.smsTaskFinish"
                  @change="changeState($event, 'smsTaskFinish')"
                />
								<div class="desc">进行中的工单被标记为完成时,发送给客户联系人</div>
							</div>
            </div>
            <div class="scope">
              <h6>应用范围</h6>
              <el-select
                v-model="messageConfig.taskFinishTaskTypeList"
                size="mini"
                multiple
                clearable
                collapse-tags
                style="width: 190px"
                placeholder="全部工单类型"
                @change="typeSelectChange('taskFinishTaskTypeList')"
              >
                <el-option v-for="item in taskTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
             
            </div>
          </div>
          <!-- 工单完成通知 end-->

          <!-- 事件分配 start-->
          <div class="setting-item">
            <div class="header">
              <div class="title">
                事件分配通知 <el-tooltip content="尊敬的客户您好，我们已经安排{user}（{umobile}）处理您的服务需求，了解进度请访问{url}"><i class="iconfont icon-fdn-info"></i></el-tooltip> 
              </div>
              <div class="switch-contain">
                <el-switch
                  v-model="messageConfig.smsEventAllot"
                  @change="changeState($event, 'smsEventAllot')"
                />
								<div class="desc">当事件被分配时，发送给客户联系人</div>
							</div>
            </div>
            <div class="scope">
              <h6>应用范围</h6>
              <el-select
                v-model="messageConfig.eventAllotEventTypeList"
                size="mini"
                multiple
                clearable
                collapse-tags
                style="width: 190px"
                placeholder="全部事件类型"
                @change="typeSelectChange('eventAllotEventTypeList')"
              >
                <el-option v-for="item in eventTypeList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
              
            </div>
          </div>
          <!-- 事件分配 end-->

          <!-- 事件完成 start-->
          <div class="setting-item">
            <div class="header">
              <div class="title">
                事件完成通知 <el-tooltip content="尊敬的客户您好，您的服务需求已由{user}（{umobile}）处理完成，状态为 ({state}) 请访问链接了解详情{url}"><i class="iconfont icon-fdn-info"></i></el-tooltip> 
              </div>
              <div class="switch-contain">
                <el-switch
                  v-model="messageConfig.smsEventFinish"
                  @change="changeState($event, 'smsEventFinish')"
                />
								<div class="desc">当事件被标记为完成时，发送给客户联系人</div>
							</div>
            </div>
            <div class="scope">
              <h6>应用范围</h6>
              <el-select
                v-model="messageConfig.eventFinishEventTypeList"
                size="mini"
                multiple
                clearable
                collapse-tags
                style="width: 190px"
                placeholder="全部事件类型"
                @change="typeSelectChange('eventFinishEventTypeList')"
              >
                <el-option v-for="item in eventTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>
          </div>
          <!-- 事件完成 end-->

          <!-- 工单计划时间提醒客户 start-->
          <div class="setting-item">
            <div class="header">
              <div class="title">
                工单计划时间提醒客户 <el-tooltip content="尊敬的客户您好，{tenant}计划{time}安排{user}联系电话{umobile}为您提供服务，客服电话{phone}。"><i class="iconfont icon-fdn-info"></i></el-tooltip> 
              </div>
              <div class="desc plan-time">
                在计划开始时间到期前
                <el-input v-model="planTimeNotice" @change="handleRemindChange"></el-input>
                小时(允许设置为小数)发送短信提醒客户，为空时不提醒
              </div>
            </div>
            <div class="scope">
              <h6>应用范围</h6>
              <el-select
                v-model="messageConfig.taskPlanTimeTaskTypeList"
                size="mini"
                multiple
                clearable
                collapse-tags
                style="width: 190px"
                placeholder="全部工单类型"
                @change="typeSelectChange('taskPlanTimeTaskTypeList')"
              >
                <el-option v-for="item in taskTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>
          </div>
          <!-- 工单计划时间提醒客户 end-->

          <!-- 客服电话 start-->
          <div class="setting-item">
            <div class="header">
              <div class="title">
                客服电话
              </div>
              <div class="desc plan-tel">配置短信中显示的统一客服电话，方便客户咨询。</div>
            </div>
            <div class="scope tel-num">
              <el-input v-model="telnum" placeholder="请输入客服电话[最多13字]" maxlength="13"></el-input>
              <el-button type="primary" @click="saveTel">保存</el-button>
            </div>
          </div>
          <!-- 客服电话 end-->
        </div>

        <el-tabs v-model="activeTab">
          <el-tab-pane label="短信充值" name="sms">
            <div class="sms-pay">
              <div class="sms-count">
                <span>短信剩余量：{{detail.smsCount}}</span>
                <el-button type="text" @click="pay">充值</el-button>
              </div>
              <div class="time-search">
                <span>按时间查询</span>
                <el-date-picker
                  v-model="datePicker"
                  style="width: 100%;"
                  type="daterange"
                  align="right"
                  unlink-panels
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="timestamp"
                  :clearable="false"
                  @change="dateChange"
                  :default-time="['00:00:00', '23:59:59']"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </div>
            </div>
            <sms-pay-record :date="datePicker" ref="smsPayRecordRef"></sms-pay-record>
          </el-tab-pane>
          <el-tab-pane label="签名设置" name="sign">
            <span class="sign-content">签名：{{sign}}<i class="iconfont icon-edit-square" @click="updateSign"></i></span>
            <p style="font-size: 13px;color: #dd4b39;margin-top: 6px;margin-bottom: 0;">说明：</p>
            <p style="font-size: 13px;color: #dd4b39;margin-top: 6px;margin-bottom: 0;">
              1.短信签名修改后所有非默认模板（含修改后的默认模板）必须重新申请</p>
            <p style="font-size: 13px;color: #dd4b39;margin-top: 6px;margin-bottom: 0;">
              2.签名可以是公司简称、网站简称、注册商标名称，3～8个字符，如 售后宝，Publink。</p>
            <p style="font-size: 13px;color: #dd4b39;margin-top: 6px;margin-bottom: 0;">
              3.签名中禁止使用特殊符号，如 【、】、& 等。</p>
          </el-tab-pane>
          <el-tab-pane label="模板设置" name="template">
            <el-button type="primary" @click="applyTpl">申请模板</el-button>
            <sms-template-record @edit="editTpl" ref="smsTemplateRecordRef"></sms-template-record>
          </el-tab-pane>
          <el-tab-pane label="发送记录" name="record">
            <sms-send-record></sms-send-record>
          </el-tab-pane>
        </el-tabs>  

      </div>
    </div>
    <sms-pay ref="smsPayRef"></sms-pay>
    <update-sign ref="signRef" @update="update"></update-sign>
    <sms-template ref="smsTemplateRef" @updateSmsTemplate="updateTpl"></sms-template>
  </div>
</template>

<script>
import { storageGet } from '@src/util/storage.ts';
import { nearDateBy, dayTimeEnd, useDatePicker } from 'pub-bbx-utils';
import * as SettingApi from '@src/api/SettingApi';
import SmsPay from './components/SmsPay.vue';
import SmsPayRecord from './components/SmsPayRecord.vue';
import UpdateSign from './components/UpdateSign.vue';
import SmsTemplate from './components/SmsTemplate.vue';
import SmsTemplateRecord from './components/SmsTemplateRecord.vue';
import SmsSendRecord from './components/SmsSendRecord.vue';

/* util */
import qs from '@src/util/querystring';
import { validatePhone } from '@src/util/validator'

export default {
  name: 'sms-message',
  components: {
    SmsPay,
    SmsPayRecord,
    UpdateSign,
    SmsTemplate,
    SmsTemplateRecord,
    SmsSendRecord,
  },
  props: {
    showNav: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    const { today, yesterday, nearDate} = useDatePicker()
    return {
      activeTab: 'sms',
      title: '',
      loading: false,
      nowMenu: 2,
      newMenuList: [],
      // 工单事件类型
      eventTypeList: [],
      taskTypeList: [],
      detail: {},
      // 短信配置
      messageConfig: {},
      planTimeNotice: 0,
      telnum: '',
      // 选择字段
      selectModule: '',
      originModules: [],
      selectModules: [
        // { moduleName: '选择模块', moduleValue: '' }
      ],
      selectField: '',
      selectFields: [
        { moduleName: '选择字段', moduleValue: '' }
      ],
      datePicker: [+nearDateBy(7, 'day'), +dayTimeEnd()],
      pickerOptions: {
        shortcuts: [
          today('今天'),
          yesterday('昨天'),
          nearDate('最近一周'),
          nearDate('最近一个月', 1, 'month'),
          nearDate('最近三个月', 3, 'month'),
        ]
      },
      sign: '',
    };
  },
  async created() {
    this.newMenuList = await this.getTabList();
    this.nowMenu = this.newMenuList.findIndex(item=>item.id === 'smsmessage')
    this.getSmsMessageInfo();
    this.$nextTick(()=>{
      this.getSign();
    });
  },
  mounted() {
    const query = qs.parse(window.location.search);
		if (query?.source === 'active') {
			const scrollHeight= this.$refs.mainRef.scrollHeight;
      this.$nextTick(() => {
        this.$refs.mainRef.scrollTop = scrollHeight;
      })
		}
	},
  methods: {
    getSign(){
      this.$http.get('/vipsms/getAutograph').then(res=>{
        this.sign = res.data;
      })
    },  
    updateSign(){
      this.$refs.signRef.openDialog(this.sign);
    },
    update(sign){
      this.sign = sign;
    },      
    update(sign){
      this.sign = sign;
    },      
    pay(){
      this.$refs.smsPayRef.openDialog();
    },
    dateChange(event) {
      this.$refs.smsPayRecordRef.search();
    },
    // 获取配置信息
    getSmsMessageInfo(){
      SettingApi.getSmsMessageInfo().then(({ status, data, message })=>{
        if(status) return this.$platform.notification({
          title: '失败',
          message: message || '',
          type: 'error'
        })
        this.detail = data;
        this.messageConfig = data.messageConfig || {};
        this.planTimeNotice = data.planTimeNotice;
        this.telnum = data.telnum || '';
        this.taskTypeList = JSON.parse(data.taskTypeListJson) || [];
        this.eventTypeList = JSON.parse(data.eventTypeListJson) || [];
      });
    },
    // 新建短信模板
    applyTpl(){
      this.$refs.smsTemplateRef.openDialog();
    },
    // 编辑短信模板
    editTpl(item){
      this.$refs.smsTemplateRef.openDialog(item);
    },
    // 新建和编辑短信模板成功后刷新列表
    updateTpl(){
      this.$refs.smsTemplateRecordRef.search();
    },
    // 切换应用类型
    async typeSelectChange(name) {
      let typeIds = this.messageConfig[name].join(',');
      // console.log('rangeList', typeIds, name);
      try {
        const { status, message } = await SettingApi.changeTypes({name, typeIds});
        if(status) return this.$platform.notification({
          title: '保存失败',
          message: message || '',
          type: 'error'
        })
      } catch (error) {
        console.log(error);
      }
    },
    // 改变模板开启禁用
    async changeState(state, message) {
      // console.log(state, message);
      try {
        const { status, message: msg } = await SettingApi.saveSmsMessage({state, message});
        if(status) return this.$platform.notification({
          title: '保存失败',
          message: msg || '',
          type: 'error'
        })
      } catch (error) {
        console.log(error);
      }
    },
    // 工单提醒计划时间
    async handleRemindChange(){
      if(!this.planTimeNotice) this.planTimeNotice = 0;
      if(parseFloat(this.planTimeNotice).toString() != 'NaN') return this.$platform.notification({
        title: '保存失败',
        message: '请输入合法数字',
        type: 'error'
      });
      try {
        const { status, message } = await SettingApi.saveSetting({planTimeNotice: this.planTimeNotice});
        if(status) {
          this.$platform.notification({
            title: '保存失败',
            message: message || '',
            type: 'error'
          })
          return
        } 
        this.$platform.notification({
          title: '保存成功',
          type: 'success'
        })
      } catch (error) {
        console.log(error);
      }
    },
    // 保存客服电话
    async saveTel(){
      // 校验400开头
      const reg = /^400[0-9]{7}/;
      if(!validatePhone(this.telnum)) {
        return this.$platform.notification({
          title: '保存失败',
          message: '请输入正确的客服电话',
          type: 'error'
        });
      }
      if(!this.telnum) return this.$platform.notification({
        title: '保存失败',
        message: '请输入客服电话',
        type: 'error'
      });
      try {
        const { status, message } = await SettingApi.saveTel({telnum: this.telnum});
        if(status) {
          this.$platform.notification({
            title: '保存失败',
            message: message || '',
            type: 'error'
          })
          return
        } 
        this.$platform.notification({
          title: '保存成功',
          type: 'success'
        })
      } catch (error) {
        console.log(error);
      }
    },
    async getTabList() {
      let messageModules = []
      try {
        messageModules = await storageGet('setting-modules', '[]', 'keyvaluepairs');
        
      } catch (error) {
        console.log(error);
      }
      return [
        {
          id: 'ddmessage',
          name: '消息设置',
          icon: 'icon-bell-fill',
          url: '/foundation/setting/message',
          show: this.isModuleShow('MESSAGE_DD_MESSAGE', messageModules)
        },
        {
          id: 'subManage',
          name: '订阅通知管理',
          icon: 'icon-dingyue',
          url: '/setting/message/subManage',
          show: this.isModuleShow('MESSAGE_SUB_MANAGE', messageModules)
        },
        {
          id: 'smsmessage',
          name: '短信消息设置',
          icon: 'icon-fuwubeizhu',
          url: '/setting/message/smsmessage',
          show: this.isModuleShow('MESSAGE_SMS_MESSAGE', messageModules)
        },
        {
          id: 'emailMessage',
          name: '邮件消息设置',
          icon: 'icon-mail-fill1',
          url: '/foundation/emailMessage',
          show: this.isModuleShow('MESSAGE_EMAIL_MESSAGE', messageModules)
        },
        {
          id: 'toastList',
          name: '消息记录',
          icon: 'icon-xitongrizhi',
          url: '/setting/doMyself/toastList', // 该页面是vue页面
          show: this.isModuleShow('MESSAGE_TOAST_LIST', messageModules)
        },
      ].filter(item=>item.show);
    },
    isModuleShow(moduleId, messageModules){
      let flag = false;
      for (let index = 0; index < messageModules.length; index++) {
        if(messageModules[index].itemName === moduleId) {
          flag = true;
          break;
        }
      }
      return flag;  
    },
    changePage(item, index) {
      if (this.nowMenu === index) {
        return;
      }
      let href = ''
      if(item.url.indexOf('/foundation/') > -1) {
        href = item.url;
      } else {
        href = `${this.$resourcePrefix}${item.url}`;
      }
      window.location.href = href;
      this.nowMenu = index;
    },
  },
};
</script>

<style lang="scss">
.sms-message-page {
  padding: 16px;
  position: relative;
  box-sizing: border-box;
  height: 100vh;
  max-width: 100vw;
  width:100%;
  .el-tag.el-tag--info{
    max-width:70%;
  }
	.sms-message-page-content {
		display: flex;
    align-items: flex-start;
    height: 100%;
		.left-menu {
      display: none;
			box-sizing: border-box;
      border-radius: 4px;
      background: #fff;
      width: 194px;
      min-width: 194px;
      height: 100%;
			.menu-title {
				padding: 0 16px;
        line-height: 48px;
        margin: 0;
        font-size: 16px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #262626;
			}
			.menu-list {
				padding: 0 16px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #595959;
        line-height: 40px;
        text-decoration: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        &:hover {
          color:#595959;
          background-color: rgba(0, 0, 0, 0.0392156863);
        }
        &.menu-checked {
          background-color: $color-primary-light-1;
          color: $color-primary-light-6;
        }
        span {
          font-size: 14px;
        }
        .icon-box {
          width: 22px;
          height: 22px;
          display: flex;
          align-items: center;
          margin-right: 10px;
          i{
            font-size: 14px;
          }
        }
      }
      
		}
		.main {
      margin-left: 10px;
      flex: 1;
      box-sizing: border-box;
      height: 100%;
      overflow-y: auto;
      border-radius: 4px;
      .sms-message-tpl {
        background: #ffffff;
        padding: 0px 16px;
        border-radius: 4px;
       
      }
      .el-tabs {
        background: #fff;
        margin-top: 12px;
        padding: 12px;
        border-radius: 4px;
      }
			.setting-item {
				padding:12px 0px;
				border-bottom: 1px dashed #E8E8E8;
        &:last-child{
          border:0;
        }
				.header {
					flex: 1;
					.plan-time,.plan-tel{
						display: flex;
						align-items: center;
            padding:18px 0 18px 10px;
            color:#595959;
            font-size: 14px;
						.el-input {
							width: 60px;
							margin: 0 4px;
						}
					}
				}
				.scope {
          h6{
						height: 22px;
						font-size: 14px;
						font-family: PingFangSC-Medium, PingFang SC;
						font-weight: 500;
						color: #262626;
						line-height: 22px;
						margin:0 0 12px 12px;
					}
					.el-select {
						margin: 0 10px;
					}
				}
				.title {
					font-size: 14px;
					font-family: PingFangSC-Medium, PingFang SC;
					font-weight: 500;
					color: #262626;
					line-height: 22px;
					margin: 0;
					display: flex;
					align-items: center;
					&::before{
						display: inline-block;
						content:'';
						margin-right: 8px;
						width: 2px;
						height: 16px;
						background: $color-primary-light-6;
					}
          i{
            margin-left:10px;
            font-size: 16px;
            color:#8C8C8C;
            font-weight: 600;
          }
					span {
						color: $color-primary;
						margin-left: 10px;
					}
				}
        .switch-contain{
					display: flex;
					padding:12px 0 12px 10px;
					.el-switch{
						height:22px;
						padding-right:10px;
					}
					.desc{
						font-size: 12px;
						font-family: PingFangSC-Regular, PingFang SC;
						font-weight: 400;
						color: var(--bbx-text-color-secondary, #8c8c8c);
						line-height: 22px;
					}
				}
			}
      .task-response-item {
        margin-top: 0;
      } 
			.setting-edit {
				margin: 0 8px;
				color: $color-primary;
				cursor: pointer;
			}
			.setting-del {
				color: #f56c6c;
				cursor: pointer;
			}
			.tip {
				color: #faae14;
				margin-top: 10px;
				p {
					margin: 8px 0;
				}
			}
			.button-setting {
				float: right;
			}
		}
	}
	.createView {
		border-radius: 8px !important;
		.el-dialog__header {
			border-radius: 8px !important;
			margin-right: 0;
		}
	}
	.select-content {
		display: flex;
		align-items: center;
		margin-top: 10px;
		.el-select {
			margin: 0 10px;
		}
	}
}
.sms-message-content-header {

}
.flex-center {
	display: flex;
	align-items: center;
	p {
		width: 60px;
	}
	i {
   cursor: pointer;
	}
	.select-file {
		display: none;
	}
}

.tel-num {
  display: flex;
  align-items: center;
  .el-input {
    min-width: 240px;
  }
  button {
    height: 32px;
    margin-left: 12px;
  }
}

.sms-pay {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .sms-count {
    button {
      margin-left: 8px;
    }
  }
  .time-search {
    display: flex;
    align-items: center;
    .el-date-editor {
      width: 240px!important;
      margin-left: 12px;
    }
  }

}
.sign-content {
  i {
    padding-left: 8px;
    color: $color-primary;
  }
}
</style>